
/**
 * 初始化
 * @param self
 * @param tiyData
 */

export const init = (self, tiyData) => {
  tiyData.tPage.total = 1;
  tiyData.tPage.startIndex = 0;
  tiyData.tPage.stepNumber = 40;
  tiyData.tPage.currentPage = 1;
  tiyData.tStatus.modalModify.isLoading = false;
  tiyData.tParam.couponType = "";
  tiyData.tParam.couponName = "";
  tiyData.tParam.couponId = "";
};

function initModel(self,tiyData){
  let couponModel ={
    id:'',
    name:'',
    title:'',
    type:100,
    state:-1,
    distributionMethod:'',
    discountRate:0,
    faceValue:0,
    threshold:0,
    validityPeriod:0,
    distributionRoles:[],
    couponCode:[],
    effectiveTimeStr:'',
    effectiveTime:'',
    uniqueType:-1,
    validityPeriodType:1
  }
  tiyData.tParam.couponModel= couponModel;

  tiyData.tData.roleTreeData.splice(0, tiyData.tData.roleTreeData.length);
  tiyData.tData.roleList.forEach(function(item){
    tiyData.tData.roleTreeData.push({title:item.name,id:item.id})
  })



}
/**
 * 查询可以发放优惠券的角色
 * @param self
 * @param tiyData
 */
export const commonData = (self, tiyData) => {
  tiyData.tData.roleList.splice(0,tiyData.tData.roleList.length);
      self.$apiRole.getDistributeCouponRole({}).then(function (response) {
        self.$Spin.hide();
        if (response.success) {
          let result = response.result;
          result.forEach(function(item){
            tiyData.tData.roleList.push(item);
          })
        } else {
          self.$Message.error(response.errorMessage);
        }
      });
};

/**
 * 新增优惠券模板
 * @param self
 * @param tiyData
 */
export const add = (self, tiyData) => {
  initModel(self,tiyData);
  self.$refs['paramCouponModel'].resetFields();
  tiyData.tStatus.modalModify.isShow = true;
  tiyData.tStatus.modalModify.isLoading = true;
};

/**
 * 编辑优惠券模板
 * @param self
 * @param tiyData
 */
export const modify = (self,tiyData,id) => {
  initModel(self,tiyData);
  self.$refs['paramCouponModel'].resetFields();
  self.$Spin.show();
  self.$apiCoupon.getCouponModelById({id:id}).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      tiyData.tStatus.modalModify.isShow = true;
      tiyData.tStatus.modalModify.isLoading = true;
      tiyData.tParam.couponModel = response.result;
      let couponModal = tiyData.tParam.couponModel;
      if(couponModal.effectiveTime!=null && couponModal.validityPeriodType == 1){
        let effectiveTime =new Date(parseInt(couponModal.effectiveTime+(new Date().getTimezoneOffset()*1000*60)));
        couponModal.effectiveTimeStr =  effectiveTime;
      }

      //权限列表json
      let roles = self.$toJson(response.result.distributionRoles);
      couponModal.distributionRoles = roles;
      //构造权限tree
      tiyData.tData.roleTreeData.splice(0,tiyData.tData.roleTreeData.length);
      // if(roles.length>0){
        tiyData.tData.roleList.forEach(function(item){
          let i = roles.filter(j=>j.id ==item.id);
          if(i!=null&&i!=''){
            tiyData.tData.roleTreeData.push({title:item.name,id:item.id,checked:true})
          }else{
            tiyData.tData.roleTreeData.push({title:item.name,id:item.id})
          }

        });
        if(couponModal.type===200){
          couponModal.discountRate = 100 - couponModal.discountRate*100;
        }
      // }
      couponModal.couponCode = self.$toJson(response.result.couponCode);
      //有效期转换成天
      if(couponModal.validityPeriodType == 1) {
        couponModal.validityPeriod = (response.result.validityPeriod / 24 / 3600 / 1000).toFixed(0);
      }
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 保存优惠券模板信息到服务器
 * @param self
 * @param tiyData
 */
export const webAddOrModify = (self, tiyData) => {
  self.$refs['paramCouponModel'].validate((valid) => {
    let coupon = tiyData.tParam.couponModel;
    if (valid) {
      switch(coupon.distributionMethod){
        case 100: //用户兑换
          if(coupon.couponCode.length <= 0){
            self.$Message.error("请添加优惠券码！");
            tiyData.tStatus.modalModify.isLoading = false;
            self.$nextTick(function () {
              tiyData.tStatus.modalModify.isLoading = true;
            });
            return;
          }
          if(coupon.uniqueType != 2 && coupon.uniqueType != 3){
            self.$Message.error('用户兑换优惠券必须选择"全局唯一"或者有效期内唯一"！');
            tiyData.tStatus.modalModify.isLoading = false;
            self.$nextTick(function () {
              tiyData.tStatus.modalModify.isLoading = true;
            });
            return;
          }
          break;
        case 200://后台发放
          let checkedRoles =self.$refs.Tree.getCheckedNodes();
          coupon.distributionRoles.splice(0, coupon.distributionRoles.length);
          if(checkedRoles.length>0){
            for(let key in checkedRoles){
              coupon.distributionRoles.push({'id':checkedRoles[key].id,'name':checkedRoles[key].title});
            }
          }else{
            self.$Message.error("请勾选允许发送此优惠券的角色！");
            tiyData.tStatus.modalModify.isLoading = false;
            self.$nextTick(function () {
              tiyData.tStatus.modalModify.isLoading = true;
            });
            return;
          }
          break;
      }

      if(coupon.validityPeriodType == 1 && coupon.effectiveTimeStr){
        let startDate = new Date(coupon.effectiveTimeStr);
        coupon.effectiveTime = Date.UTC(startDate.getFullYear(),startDate.getMonth(),startDate.getDate(),startDate.getHours());
      } else {
        coupon.effectiveTime = "";
      }
      let msg = "当前优惠券面值为";
      if(coupon.type == 100){
        msg += ("满$" + coupon.threshold + "减$" + coupon.faceValue);
      } else {
        msg += ("满$" + coupon.threshold + "减" + coupon.discountRate + "%");
      }

      switch(coupon.validityPeriodType){
        case 1:
          if(coupon.effectiveTime){
            msg += ("，有效期自" + self.$tiyBJTime(coupon.effectiveTime) + "开始");
          } else {
            msg += ("，有效期为" + coupon.validityPeriod +"天。请您二次确认。");
          }
          break;
        case 2:
          msg += ("，有效期为当月有效。请您二次确认。");
          msg += ("新用户审核后会按照新规则发放优惠券！");
          break;
        default:
          break;
      }
      self.$Modal.confirm({
        title: "确认",
        content: msg,
        onOk: () => {
          //有效期转换成毫秒
          if(coupon.validityPeriodType == 1){
           coupon.validityPeriod = coupon.validityPeriod*24*3600*1000;
          }

          if(coupon.type==200){
            coupon.discountRate = 1 - coupon.discountRate/100.0;
          }
          self.$Spin.show();
          self.$apiCoupon.addOrEditCouponModel({couponModel: JSON.stringify(coupon)}).then(function(response){
            self.$Spin.hide();
            tiyData.tStatus.modalModify.isLoading = false;
            tiyData.tStatus.modalModify.isShow = false;
            if (response.success) {
              self.$Message.info("保存成功!");
              webList(self, tiyData);
            } else {
              self.$Message.error(response.errorMessage);
            }
          });
        },
        onCancel:() => {
          tiyData.tStatus.modalModify.isLoading = false;
        }
      });

    } else {
      tiyData.tStatus.modalModify.isLoading = false;
      self.$nextTick(function () {
        tiyData.tStatus.modalModify.isLoading = true;
      });
    }
  });
};

/**
 * 查询优惠券模板列表
 * @param self
 * @param tiyData
 */
export const webList = (self, tiyData) => {
  self.$Spin.show();
  self.$apiCoupon.getCouponModelList({
    "couponType":tiyData.tParam.couponType,
    "pageNum":tiyData.tPage.currentPage,
    "pageSize":tiyData.tPage.stepNumber
  }).then(function (response){
    self.$Spin.hide();
    if (response.success) {
      tiyData.tData.couponModelList.splice(0, tiyData.tData.couponModelList.length);
      let couponPage = response.result;
      tiyData.tPage.total = couponPage.total;
      tiyData.tPage.stepNumber = couponPage.pageSize;
      couponPage.list.forEach(
        function (item) {
          tiyData.tData.couponModelList.push(item);
        }
      );
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};

/**
 * 启用/禁用模板
 * @param self
 * @param tiyData
 */
export const changeState = (self, tiyData,id,state, title) => {
  self.$Spin.show();
  self.$apiCoupon.changeCouponModelState({
    "id":id,
    "state":state,
    "title":title
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.info("操作成功!");
      webList(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
    tiyData.tStatus.modalAction.isShow  = false;
  });
};

/**
 * 删除模板
 * @param self
 * @param tiyData
 */
export const deleteCouponDefine = (self, tiyData,id, title) => {
  self.$Spin.show();
  self.$apiCoupon.deleteCouponDefine({
    "id":id,
    "title":title
  }).then(function (response) {
    self.$Spin.hide();
    if (response.success) {
      self.$Message.info("删除成功!");
      webList(self, tiyData);
    } else {
      self.$Message.error(response.errorMessage);
    }
  });
};
